package com.bkhech.home.practice.spring.ant_matcher;

import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Map;

/**
 * Spring ant 模式匹配
 * <p>
 * Ant风格的路径匹配器。 来自Spring-core和Ant
 * 匹配URL的规则如下：
 * ? 匹配单个字符
 * * 匹配0个或多个字符
 * ** 0个或多个路径中的目录节点
 * {filename:[a-z]+} 匹配以"filename"命名的正则 [a-z]+
 * <p>
 * {@link cn.hutool.core.text.AntPathMatcher } 抄的 {@link org.springframework.util.AntPathMatcher}
 *
 * @author guowm
 * @date 2023/1/12
 * @see cn.hutool.core.text.AntPathMatcher
 */
public class AntMatcherDemo {

    static final org.springframework.util.AntPathMatcher antPathMatcher = new AntPathMatcher();

    public static void main(String[] args) throws IOException {
        antMatcher();
    }

    private static void antMatcher() {
        // 1 匹配URL的规则
        // 注意： String pattern = "/com/*/bb" 匹配不到 "/com/bb"
        String pattern10 = "/com/*/bb";
        String pattern11 = "/com/**/bb";
        String path = "/com/bb";
        // false
        System.out.println(antPathMatcher.match(pattern10, path));
        // true
        System.out.println(antPathMatcher.match(pattern11, path));

        // 2 匹配URL的规则
        // 匹配以"id"命名的正则 d+ (只能为数字)
        String pattern20 = "com/{id:\\d+}.java";
        String path20 = "com/test.java";
        String path21 = "com/1.java";
        // false
        System.out.println(antPathMatcher.match(pattern20, path20));
        // true
        System.out.println(antPathMatcher.match(pattern20, path21));

        String pattern30 = "/docs/cvs/*.html";
        String path30 = "/docs/cvs/commit.html";
        String pattern31 = "com/{id:\\d+}.java";
        String path31 = "com/1.java";
        //'/docs/*' and '/docs/cvs/commit → 'cvs/commit'
        //'/docs/cvs/*.html' and '/docs/cvs/commit.html → 'commit.html'
        // "com/{id:\\d+}.java" and "com/1.java" ->  //为空，注意： 花括号正则不好使
        final String extractPathWithinPattern30 = antPathMatcher.extractPathWithinPattern(pattern30, path30);
        System.out.println(extractPathWithinPattern30);
        // 注意： 花括号正则不好使
        final String extractPathWithinPattern1 = antPathMatcher.extractPathWithinPattern(pattern31, path31);
        System.out.println(extractPathWithinPattern1);

        String pattern40 = "/docs/cvs/{filename}.html";
        String path40 = "/docs/cvs/commit.html";
        String pattern41 = "com/{id:\\d+}.java";
        String path41 = "com/1.java";
        // "/docs/cvs/{filename}.html" and "/docs/cvs/commit.html" -> {filename=commit}
        // "com/{id:\\d+}.java" and "com/1.java" -> {id=1}
        final Map<String, String> extractUriTemplateVariables40 = antPathMatcher.extractUriTemplateVariables(pattern40, path40);
        System.out.println(extractUriTemplateVariables40);
        final Map<String, String> extractUriTemplateVariables41 = antPathMatcher.extractUriTemplateVariables(pattern41, path41);
        System.out.println(extractUriTemplateVariables41);
    }

}
